import sys

from tcping import Ping


def process_arguments(args):
    """
    处理命令行参数
    """
    length = len(args)
    if length == 1 or length > 3:
        print("Usage: nping <address> [port]")
        sys.exit(1)
    add = args[1]
    p = int(args[2]) if length == 3 else 80
    return add, p


def ping(address, port):
    """
    执行 ping 操作
    """
    ping_info = Ping(address, port, timeout=60)
    ping_info.ping(5)

    # 输出 ping 结果
    print("Ping results:")
    for row in ping_info.result.rows:
        print(row)

    print("Raw result:", ping_info.result.raw)
    print("Table result:", ping_info.result.table)


if __name__ == '__main__':
    try:
        # 处理命令行参数
        address, port = process_arguments(sys.argv)
        # 执行 ping 操作
        ping(address, port)
    except Exception as e:
        print(f"An error occurred: {e}")
